package com.zxl.gtion.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.google.common.base.Charsets;
import com.zxl.gtion.pojo.BaiduErnie4Message;
import com.zxl.gtion.pojo.BaiduErnie4VO;
import com.zxl.gtion.util.BaiDuUtil;
import com.zxl.gtion.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * (Topic)表控制层
 *
 * @author 
 * @since 2024-03-06 16:45:08
 */
@RestController
@RequestMapping("baidu")
public class BaiduController {
    /**
     * 服务对象
     */
    @Autowired
    private BaiDuUtil baiDuUtil;

    @PostMapping("ernie4")
    @ApiOperation("百度文心一言ernie4")
    public R ernie4(@RequestBody BaiduErnie4Message message){
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + baiDuUtil.getAccessToken();
        String messageStr = JSON.toJSONString(message);
        long l = System.currentTimeMillis();
        HttpResponse response = HttpRequest.post(url)
                .charset(Charsets.UTF_8)
                .method(Method.POST)
                .body(messageStr)
                .header("Content-type", "application/json")
                .execute();
        long l1 = System.currentTimeMillis();
        System.out.println("response = " + response);
        long l2 = l1-l;
        System.out.println("调用时间：" + l2);
        if (response.getStatus() == 200) {
            BaiduErnie4VO baiduErnie4VO = JSON.parseObject(response.body(), BaiduErnie4VO.class);
            List<BaiduErnie4Message.Message> messages = message.getMessages();
            BaiduErnie4Message.Message newMassage = new BaiduErnie4Message.Message();
            newMassage.setRole("assistant");
            newMassage.setContent(baiduErnie4VO.getResult());
            messages.add(newMassage);
            return R.ok(messages);
        }

        return R.ok();
    }


}

